<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      :destroy-on-close="true"
      :width="!props.isReadonly ? '1100px' : '1100px'"
      :align-center="true"
      draggable
      style="min-width: 1100px"
      @close="closeDialog"
      class="maxhDialog"
    >
      <div v-show="props.isReadonly">
        <el-tabs>
          <el-tab-pane label="基本信息"
            ><div>
              <!-- <h3
                class="mb-[5px] mt-[-15px] c-[#333] text-[15px] font-600 lh-[28px]"
              >
                设备信息
              </h3> -->
              <el-descriptions
                title=""
                :column="3"
                border
                style="width: 99%; margin-bottom: 20px"
              >
                <el-descriptions-item>
                  <template #label>
                    <div class="cell-item">设备名称</div>
                  </template>
                  {{ formData.assetName || "" }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template #label>
                    <div class="cell-item">设备编码</div>
                  </template>
                  {{ formData.assetCode || "" }}
                </el-descriptions-item>
                <el-descriptions-item v-show="formData.assetTypeName">
                  <template #label>
                    <div class="cell-item">设备种类</div>
                  </template>
                  {{ formData.assetTypeName || "" }}
                </el-descriptions-item>
                <el-descriptions-item v-if="formData.assetModelNo">
                  <template #label>
                    <div class="cell-item">品牌型号</div>
                  </template>
                  {{ formData.assetModelNo || "" }}
                </el-descriptions-item>
                <el-descriptions-item v-if="formData.usingDepartmentName">
                  <template #label>
                    <div class="cell-item">使用部门</div>
                  </template>
                  {{ formData.usingDepartmentName || "" }}
                </el-descriptions-item>
                <el-descriptions-item v-if="formData.usingPersonName">
                  <template #label>
                    <div class="cell-item">使用人</div>
                  </template>
                  {{ formData.usingPersonName || "" }}
                </el-descriptions-item>
                <el-descriptions-item v-if="formData.locationName">
                  <template #label>
                    <div class="cell-item">设备位置</div>
                  </template>
                  {{ formData.locationName || "" }}
                </el-descriptions-item>
              </el-descriptions>

              <h3
                class="mb-[5px] mt-[-3px] c-[#333] text-[15px] font-600 lh-[28px]"
              >
                故障信息
              </h3>
              <el-descriptions
                title=""
                :column="3"
                border
                style="width: 99%; margin-bottom: 20px"
              >
                <el-descriptions-item>
                  <template #label>
                    <div class="cell-item">故障时间</div>
                  </template>
                  {{ formData?.timeOfFailure || "" }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template #label>
                    <div class="cell-item">报修时间</div>
                  </template>
                  {{ formData.repairTime || "" }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template #label>
                    <div class="cell-item">报修人</div>
                  </template>
                  {{ formData.repairUserName || "" }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template #label>
                    <div class="cell-item">报修编号</div>
                  </template>
                  {{ formData.repairCode || "" }}
                  <el-tag
                    type="warning"
                    class="ml-[5px] mt-[-2px]"
                    v-if="formData.repairStatus == '0'"
                    >{{
                      dictionaryStore.filterDictName(
                        "EamRepairStatus",
                        formData.repairStatus
                      )
                    }}</el-tag
                  >
                  <el-tag
                    class="ml-[5px] mt-[-2px]"
                    v-if="
                      Number(formData.repairStatus) > 0 &&
                      Number(formData.repairStatus) < 4
                    "
                    >{{
                      dictionaryStore.filterDictName(
                        "EamRepairStatus",
                        formData.repairStatus
                      )
                    }}</el-tag
                  >
                  <el-tag
                    class="ml-[5px] mt-[-2px]"
                    type="info"
                    v-if="Number(formData.repairStatus) >= 4"
                    >{{
                      dictionaryStore.filterDictName(
                        "EamRepairStatus",
                        formData.repairStatus
                      )
                    }}</el-tag
                  >
                </el-descriptions-item>
                <el-descriptions-item>
                  <template #label>
                    <div class="cell-item">故障状态</div>
                  </template>
                  {{
                    dictionaryStore.filterDictName(
                      "EamFaultStatus",
                      formData.faultStatus
                    )
                  }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template #label>
                    <div class="cell-item">故障等级</div>
                  </template>
                  <el-tag v-if="formData.repairLevel == '1'" type="danger">{{
                    dictionaryStore.filterDictName(
                      "EamFaultLevel",
                      formData.repairLevel
                    )
                  }}</el-tag>
                  <el-tag v-else>{{
                    dictionaryStore.filterDictName(
                      "EamFaultLevel",
                      formData.repairLevel
                    )
                  }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item>
                  <template #label>
                    <div class="cell-item">故障来源</div>
                  </template>
                  {{
                    dictionaryStore.filterDictName(
                      "EamFaultSource",
                      formData.repairSource
                    )
                  }}
                </el-descriptions-item>
                <el-descriptions-item :span="3">
                  <template #label>
                    <div class="cell-item">故障描述</div>
                  </template>
                  {{ formData.remarks || "" }}
                </el-descriptions-item>
                <el-descriptions-item
                  v-if="formData.images && formData.images.length"
                  :span="3"
                >
                  <template #label>
                    <div class="cell-item">故障图片</div>
                  </template>
                  <div style="margin-bottom: -10px">
                    <CommonUploadFile
                      :showText="false"
                      :isRead="props.isReadonly"
                      :files="formData.images"
                      :key="1"
                    />
                  </div>
                </el-descriptions-item>
              </el-descriptions>
              <div>
                <h3
                  class="mb-[5px] mt-[-3px] c-[#333] text-[15px] font-600 lh-[28px]"
                >
                  维修信息
                </h3>
                <div
                  class="grey1-color flex justify-start"
                  style="margin-bottom: 12px; color: #c0c4cc"
                  v-if="
                    !formData.repairTeamName &&
                    !formData.repairTeamUserName &&
                    !formData?.answerTime &&
                    formData?.outSourcing != '1'
                  "
                >
                  待维修人员响应，暂无信息
                </div>
                <el-descriptions
                  title=""
                  :column="3"
                  border
                  v-else
                  style="width: 99%; margin-bottom: 20px"
                >
                  <el-descriptions-item v-if="formData.answerTime">
                    <template #label>
                      <div class="cell-item">应答时间</div>
                    </template>
                    {{ formData.answerTime || "" }}
                  </el-descriptions-item>
                  <el-descriptions-item v-if="formData.repairStartTime">
                    <template #label>
                      <div class="cell-item">维修开始时间</div>
                    </template>
                    {{ formData.repairStartTime || "" }}
                  </el-descriptions-item>
                  <el-descriptions-item v-if="formData.repairEndTime">
                    <template #label>
                      <div class="cell-item">维修结束时间</div>
                    </template>
                    {{ formData.repairEndTime || "" }}
                  </el-descriptions-item>
                  <el-descriptions-item v-if="formData.faultMode">
                    <template #label>
                      <div class="cell-item">故障模式</div>
                    </template>
                    {{ formData.faultMode || "" }}
                  </el-descriptions-item>
                  <el-descriptions-item v-if="formData.faultPhenomenon">
                    <template #label>
                      <div class="cell-item">故障现象</div>
                    </template>
                    {{ formData.faultPhenomenon || "" }}
                  </el-descriptions-item>
                  <el-descriptions-item v-if="formData.faultReason">
                    <template #label>
                      <div class="cell-item">故障原因</div>
                    </template>
                    {{ formData.faultReason || "" }}
                  </el-descriptions-item>
                  <el-descriptions-item v-if="formData.faultPosition">
                    <template #label>
                      <div class="cell-item">故障部位</div>
                    </template>
                    {{ formData.faultPosition || "" }}
                  </el-descriptions-item>
                  <el-descriptions-item
                    :span="2"
                    v-if="formData.faultHandleMeasure"
                  >
                    <template #label>
                      <div class="cell-item">处理措施</div>
                    </template>
                    {{ formData.faultHandleMeasure || "" }}
                  </el-descriptions-item>
                  <el-descriptions-item v-if="formData.repairTeamName">
                    <template #label>
                      <div class="cell-item">维修班组</div>
                    </template>
                    <!-- {{ formData.repairTeamCode || "" }} - -->
                    {{ formData.repairTeamName || "" }}
                  </el-descriptions-item>
                  <el-descriptions-item
                    v-if="
                      formData.repairTeamUserName &&
                      (!formData?.repairOrderPersons ||
                        formData?.repairOrderPersons.length === 0)
                    "
                  >
                    <template #label>
                      <div class="cell-item">维修人员</div>
                    </template>
                    <span>
                      <!-- {{ formData.repairTeamUserEmpNo || "" }} - -->
                      {{ formData.repairTeamUserName || "" }}
                    </span>
                  </el-descriptions-item>
                  <el-descriptions-item
                    v-if="
                      formData?.repairOrderPersons &&
                      formData?.repairOrderPersons.length
                    "
                  >
                    <template #label>
                      <div class="cell-item">维修人员</div>
                    </template>
                    <span>
                      {{ getRepairOrderPersons(formData?.repairOrderPersons) }}
                    </span>
                  </el-descriptions-item>
                  <el-descriptions-item v-if="formData.repairUseTime">
                    <template #label>
                      <div class="cell-item">维修用时</div>
                    </template>
                    {{ formData.repairUseTime || "" }}分钟
                  </el-descriptions-item>
                  <el-descriptions-item v-if="formData?.outSourcing == '1'">
                    <template #label>
                      <div class="cell-item">是否委外</div>
                    </template>
                    是
                  </el-descriptions-item>
                  <el-descriptions-item
                    :span="3"
                    v-if="formData?.repairSituation"
                  >
                    <template #label>
                      <div class="cell-item">维修其他发现</div>
                    </template>
                    {{ formData.repairSituation || "" }}
                  </el-descriptions-item>
                  <el-descriptions-item
                    v-if="formData.executeFiles && formData.executeFiles.length"
                    :span="3"
                  >
                    <template #label>
                      <div class="cell-item">维修图片</div>
                    </template>
                    <div style="margin-bottom: -10px">
                      <CommonUploadFile
                        :showText="false"
                        :isRead="props.isReadonly"
                        :files="formData.executeFiles"
                        :key="2"
                        folderName="eam/equ/eamRepairOrders"
                      />
                    </div>
                  </el-descriptions-item>
                </el-descriptions>
              </div>

              <!-- 模拟更换备件信息 -->
              <div v-if="formData.parts && formData.parts.length">
                <h3
                  class="mb-[5px] mt-[-3px] c-[#333] text-[15px] font-600 lh-[28px]"
                >
                  更换备件
                </h3>

                <el-table
                  :data="formData.parts"
                  highlight-current-row
                  border
                  :cell-style="{ 'text-align': 'center' }"
                >
                  <el-table-column
                    label="备件编号"
                    prop="spareCode"
                    width="175"
                  />
                  <el-table-column label="备件名称" prop="spareName" />
                  <el-table-column
                    label="备件类型"
                    prop="spareType"
                    width="175"
                  >
                    <template #default="scope">
                      {{
                        dictionaryStore.filterDictName(
                          "SpareType",
                          scope.row.spareType
                        )
                      }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="使用数量"
                    prop="sparePartNumber"
                    width="175"
                  />
                  <el-table-column
                    label="数量单位"
                    prop="spareUnit"
                    width="175"
                  />
                </el-table>
              </div></div
          ></el-tab-pane>
          <el-tab-pane label="操作历史">
            <div style="display: flex">
              <el-timeline
                style="
                  max-height: 100%;
                  overflow: auto;
                  padding-left: 5px;
                  margin-top: 10px;
                  min-height: 400px;
                "
              >
                <el-timeline-item
                  v-for="self in operationRecordList"
                  :key="self.id"
                  :type="typeBack(self)"
                  size="large"
                  :timestamp="self.lastUpdateTime"
                >
                  <div
                    style="
                      width: 100%;
                      word-break: break-all;
                      display: flex;
                      flex-direction: column;
                    "
                  >
                    <span style="font-weight: 400; font-size: 14px">
                      {{ self.lastUpdatedUserName }}
                      【{{ self.operateType }}】{{
                        self.operateType === "关闭" ||
                        self.operateType === "重新维修"
                          ? `&nbsp;&nbsp;原因：${self.operateResult}`
                          : ""
                      }}
                      {{
                        self.operateType === "转交" ||
                        self.operateType === "指派"
                          ? `&nbsp;&nbsp;${self.operateResult}`
                          : ""
                      }}</span
                    >
                  </div>
                </el-timeline-item>
              </el-timeline>
              <div
                style="
                  font-weight: 700;
                  font-size: 12px;
                  color: #a36c51;
                  position: absolute;
                  right: 15px;
                  top: 15px;
                  cursor: pointer;
                  height: 30px;
                  width: 50px;
                "
                @click="showOperationRecord"
              >
                <i-ep-sort /> 排序
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      <el-form
        v-show="!props.isReadonly"
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120"
        style="width: 99%; margin-top: 15px"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="设备" prop="assetName" style="width: 100%">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.assetName"
                placeholder="请选择设备"
                @focus="openSelectDialog()"
              />
              <span v-else>{{ formData.assetName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="设备编码" prop="assetCode" style="width: 100%">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.assetCode"
                placeholder="请输入设备编码"
                disabled
                clearable
              />
              <span v-else>{{ formData.assetCode }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="设备种类"
              prop="assetTypeName"
              style="width: 100%"
            >
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.assetTypeName"
                placeholder="请输入设备种类"
                disabled
                clearable
              />
              <span v-else>{{ formData.assetTypeName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="品牌型号"
              prop="assetModelNo"
              style="width: 100%"
            >
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.assetModelNo"
                placeholder="请输入品牌型号"
                disabled
                clearable
              />
              <span v-else>{{ formData.assetModelNo }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="使用部门"
              prop="usingDepartmentName"
              style="width: 100%"
            >
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.usingDepartmentName"
                placeholder="请输入使用部门"
                disabled
                clearable
              />
              <span v-else>{{ formData.usingDepartmentName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="使用人"
              prop="usingPersonName"
              style="width: 100%"
            >
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.usingPersonName"
                placeholder="请输入使用人"
                disabled
                clearable
              />
              <span v-else>{{ formData.usingPersonName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="设备位置"
              prop="locationName"
              style="width: 100%"
            >
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.locationName"
                placeholder="请输入设备位置"
                disabled
                clearable
              />
              <span v-else>{{ formData.locationName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="故障状态" prop="faultStatus">
              <el-select
                style="width: 100%"
                v-if="!props.isReadonly"
                v-model="formData.faultStatus"
                placeholder="请选择故障状态"
                clearable
              >
                <el-option
                  v-for="item in dictionaryStore.filterDictList(
                    'EamFaultStatus'
                  )"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>

              <span v-else>{{
                dictionaryStore.filterDictName(
                  "EamFaultStatus",
                  formData.faultStatus
                )
              }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="故障等级" prop="repairLevel">
              <el-select
                style="width: 100%"
                v-if="!props.isReadonly"
                v-model="formData.repairLevel"
                placeholder="请选择故障等级"
                clearable
              >
                <el-option
                  v-for="item in dictionaryStore.filterDictList(
                    'EamFaultLevel'
                  )"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>

              <span v-else>{{
                dictionaryStore.filterDictName(
                  "EamFaultLevel",
                  formData.repairLevel
                )
              }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="故障描述" prop="remarks">
              <el-input
                type="textarea"
                v-model="formData.remarks"
                placeholder="请输入故障描述"
                show-word-limit
                :maxlength="250"
                :autosize="{ minRows: 2, maxRows: 3 }"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="故障图片">
              <CommonUploadFile
                accept=".png,.jpeg,.jpg"
                :isRead="props.isReadonly"
                :files="formData.images"
                @update-files="updateFormFiles"
                :key="3"
                folderName="eam/equ/eamRepairOrders"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="故障时间" prop="timeOfFailure">
              <el-date-picker
                v-if="!props.isReadonly"
                v-model="formData.timeOfFailure"
                value-format="YYYY-MM-DD HH:mm"
                format="YYYY-MM-DD HH:mm"
                time-format="HH:mm"
                clearable
                type="datetime"
                placeholder="请选择故障时间"
                @change="timeChange"
              />
              <span v-else>{{ formData.timeOfFailure }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="维修班组" prop="repairTeamId">
              <el-select
                v-if="!props.isReadonly"
                v-model="formData.repairTeamId"
                placeholder="请输入维修班组"
                clearable
                style="width: 300px"
                @change="changeCrew"
                filterable
              >
                <el-option
                  v-for="item in crewList"
                  :key="item.id"
                  :label="`${item.teamName}`"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="维修人" prop="repairTeamUser">
              <el-select
                v-if="!props.isReadonly"
                v-model="formData.repairTeamUser"
                placeholder="请选择维修人"
                clearable
                style="width: 300px"
                :disabled="formData.repairTeamId === ''"
                @change="changeMember"
                filterable
              >
                <el-option
                  v-for="item in memberList"
                  :key="item.id"
                  :label="`${item.memberName}`"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button
            v-if="props.isReadonly && formData.repairStatus == '0'"
            type="primary"
            @click="openPrompt(5)"
            >故障取消</el-button
          >
          <el-button
            v-if="
              props.isReadonly &&
              (formData.repairStatus == '1' || formData.repairStatus == '2')
            "
            type="primary"
            @click="openPrompt(6)"
            >故障关闭</el-button
          >
          <el-button
            v-if="props.isReadonly && formData.repairStatus == '3'"
            type="primary"
            @click="openPrompt(2)"
            >重新维修</el-button
          >
          <el-button
            v-if="props.isReadonly && formData.repairStatus == '3'"
            type="primary"
            @click="openPrompt(4)"
            >完成确认</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <SelectDeviceDialog-Eam
      v-model:visible="selectDialog.visible"
      :data="selectDialog.data"
      :isMultiple="false"
      @echo-info="changeVisible"
    />
    <el-dialog
      :close-on-click-modal="false"
      v-model="showImport"
      title="提示"
      destroy-on-close
      :width="450"
      draggable
      align-center
      class="showImport"
    >
      <el-form v-if="promptStatus === 6 || promptStatus === 2">
        <el-form-item
          :label="promptStatus === 6 ? '故障原因' : '返修原因'"
          :label-width="80"
        >
          <el-input
            v-model="promptReason"
            :placeholder="promptText"
            autocomplete="off"
          />
        </el-form-item>
      </el-form>
      <div v-else>
        {{ promptText }}
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelImport">取消</el-button>
          <el-button type="primary" @click="confirmImport"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();
import { getCrewMemberListApi, getCrewListApi } from "@/utils/commonData";
import { useUserStore } from "@/store/modules/user";
import dayjs from "dayjs";

defineOptions({
  name: "EAMEAMREPAIRORDERADDORUPDATE",
  inheritAttrs: false,
});

const userStore = useUserStore();
const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  assetKind: {
    type: Number,
    default: null,
  },
  // 报修来源 按照字典表来 EamFaultSource
  repairSource: {
    type: String,
    default: "1",
  },
});

function timeChange() {
  if (formData.timeOfFailure) {
    formRef.value.validateField("timeOfFailure");
  }
}

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      if (!props.data.id) {
        formData.timeOfFailure = dayjs().format("YYYY-MM-DD HH:mm:ss");
      }
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  assetName: [{ required: true, message: "请选择设备", trigger: "blur" }],
  faultStatus: [
    { required: true, message: "请选择故障状态", trigger: "change" },
  ],
  repairLevel: [
    { required: true, message: "请选择故障等级", trigger: "change" },
  ],
  timeOfFailure: [
    { required: true, message: "请选择故障时间", trigger: "change" },
  ],

  // assetTypeId: [
  //   { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  // ],
  repairTime: [],
  repairUserName: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  repairTeamId: [{ message: "请选择维修班组", trigger: "change" }],
  repairTeamUser: [{ message: "请选择维修人", trigger: "change" }],
  remarks: [
    {
      required: true,
      min: 1,
      max: 255,
      message: "请输入故障描述",
      trigger: "blur",
    },
  ],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  // 设备信息
  assetId: "",
  assetName: "",
  assetCode: "",
  assetTypeName: "",
  assetModelNo: "",
  assetBrandName: "",
  usingDepartmentName: "",
  usingPersonName: "",
  locationName: "",
  // 故障信息
  images: [],
  parts: [],
  executeFiles: [],
  repairOrderPersons: [],
  faultStatus: "1",
  repairLevel: "1",
  timeOfFailure: "",
  remarks: "",

  // 维修信息
  repairTeamId: "",
  repairTeamCode: "",
  repairTeamName: "",
  repairTeamUser: "",
  repairTeamUserName: "",
  repairTeamUserEmpNo: "",

  // 以下为原生数据
  version: "",
  // assetTypeId: "",
  repairTime: "",
  repairUser: userStore.user.userId,
  repairUserName: userStore.user.userName,
  repairCode: "",
  answerTime: "",
  repairStartTime: "",
  repairEndTime: "",
  faultMode: "",
  faultPhenomenon: "",
  faultReason: "",
  faultPosition: "",
  faultHandleMeasure: "",
  repairSituation: "",
  repairStatus: "",
  outSourcing: "",
  repairUseTime: "", // 最新维修耗时
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
  assetKind: props.assetKind,
  repairSource: props.repairSource,

  pointCheckDetailId: "",
});

watch(
  () => props.data,
  async (newVal: any) => {
    formData.id = "";
    formData.timeOfFailure = dayjs().format("YYYY-MM-DD HH:mm:ss");
    if (newVal?.id) {
      const {
        id,
        version,
        assetTypeId,
        repairTime,
        repairUser,
        repairUserName,
        repairCode,
        answerTime,
        repairStartTime,
        repairEndTime,
        faultMode,
        faultPhenomenon,
        faultReason,
        faultPosition,
        faultHandleMeasure,
        repairSituation,
        repairStatus,
        repairOrderPersons,
        outSourcing,
        repairUseTime,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
        assetKind,
        // 设备信息
        assetId,
        assetName,
        assetCode,
        assetTypeName,
        assetModelNo,
        assetBrandName,
        usingDepartmentName,
        usingPersonName,
        locationName,
        // 故障信息
        images,
        parts,
        executeFiles,
        faultStatus,
        timeOfFailure,
        repairLevel,
        remarks,

        // 维修信息
        repairTeamId,
        repairTeamCode,
        repairTeamName,
        repairTeamUser,
        repairTeamUserName,
        repairTeamUserEmpNo,
        repairSource,
        // 异常报修id
        pointCheckDetailId,
      } = newVal;
      Object.assign(formData, {
        id,
        version,
        assetTypeId,
        repairTime,
        repairUser,
        repairUserName,
        repairCode,
        answerTime,
        repairStartTime,
        repairEndTime,
        faultMode,
        faultPhenomenon,
        faultReason,
        faultPosition,
        faultHandleMeasure,
        repairSituation,
        repairStatus,
        outSourcing,
        repairUseTime,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
        timeOfFailure,
        assetKind,
        // 设备信息
        assetId,
        assetName,
        assetCode,
        assetTypeName,
        assetModelNo,
        assetBrandName,
        usingDepartmentName,
        usingPersonName,
        locationName,
        // 故障信息
        repairOrderPersons: repairOrderPersons ?? [],
        images: images ?? [],
        parts: parts ?? [],
        executeFiles: executeFiles ?? [],
        faultStatus,
        repairLevel,
        remarks,

        // 维修信息
        repairTeamId,
        repairTeamCode,
        repairTeamName,
        repairTeamUser,
        repairTeamUserName,
        repairTeamUserEmpNo,
        repairSource,

        pointCheckDetailId,
      });
      // 品牌型号赋值
      if (assetModelNo && assetBrandName) {
        formData.assetModelNo = `${assetModelNo}-${assetBrandName}`;
      } else if (assetModelNo && !assetBrandName) {
        formData.assetModelNo = `${assetModelNo}`;
      } else if (!assetModelNo && assetBrandName) {
        formData.assetModelNo = `${assetBrandName}`;
      }
      getCrews();
      memberList.value =
        (await getCrewMemberListApi({ id: formData.repairTeamId })) || [];

      if (newVal?.id) {
        // 获取历史记录接口
        getHistoryList();
      }

      // changeCrew(repairTeamId);
    } else {
      formData.assetModelNo = "";
      formData.images = [];
      formData.parts = [];
      formData.executeFiles = [];
      formData.repairOrderPersons = [];

      formData.assetKind = props.assetKind;
      formData.repairSource = props.repairSource;
      formData.repairUserName = userStore.user.userName;

      // 异常创建设备报修单
      if (newVal?.pointCheckDetailId) {
        formData.remarks = newVal?.remarks;
        formData.pointCheckDetailId = newVal?.pointCheckDetailId;
        formData.repairTime = newVal?.workTime;
        request({
          url: `/eam/equAssetInfo/get/${newVal.assetId}`,
          method: "get",
        })
          .then((res: any) => {
            const data = res.data;
            formData.assetId = data.id;
            formData.assetCode = data.assetCode;
            formData.assetName = data.assetName;
            formData.locationName = data.locationName;
            formData.assetTypeName = data.assetTypeName;
            formData.usingDepartmentName = data.usingDepartmentName;
            formData.usingPersonName = data.usingPersonName;
            if (data.assetModelNo && data.assetBrandName) {
              formData.assetModelNo = `${data.assetModelNo}-${data.assetBrandName}`;
            } else if (data.assetModelNo && !data.assetBrandName) {
              formData.assetModelNo = `${data.assetModelNo}`;
            } else if (!data.assetModelNo && data.assetBrandName) {
              formData.assetModelNo = `${data.assetBrandName}`;
            }
          })
          .catch((res) => {
            console.log(res);
          });
      }
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.version = "";
  formData.repairTime = "";
  formData.repairUser = userStore.user.userId;
  formData.repairUserName = userStore.user.userName;
  formData.repairCode = "";
  formData.answerTime = "";
  formData.repairStartTime = "";
  formData.repairEndTime = "";
  formData.faultMode = "";
  formData.faultPhenomenon = "";
  formData.faultReason = "";
  formData.faultPosition = "";
  formData.faultHandleMeasure = "";
  formData.repairSituation = "";
  formData.repairStatus = "";
  formData.outSourcing = "";
  formData.repairUseTime = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = "";
  formData.deleted = "";
  formData.assetKind = props.assetKind;

  formData.assetId = "";
  formData.assetName = "";
  formData.assetCode = "";
  formData.assetTypeName = "";
  formData.assetModelNo = "";
  formData.assetBrandName = "";
  formData.usingDepartmentName = "";
  formData.usingPersonName = "";
  formData.locationName = "";
  formData.images = [];
  formData.parts = [];
  formData.executeFiles = [];
  formData.repairOrderPersons = [];

  formData.faultStatus = "1";
  formData.repairLevel = "1";
  formData.remarks = "";
  formData.repairTeamId = "";
  formData.repairTeamCode = "";
  formData.repairTeamName = "";
  formData.repairTeamUser = "";
  formData.repairTeamUserName = "";
  formData.repairTeamUserEmpNo = "";
  formData.repairSource = props.repairSource;

  formData.pointCheckDetailId = "";
}

const loading = ref(false);

/** 维修单保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "报修";
      await request({
        url: "/eam/eamrepairorder/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

//  点击设备
function openSelectDialog() {
  selectDialog.visible = true;
  selectDialog.data = formData.assetId
    ? [
        {
          id: formData.assetId,
          assetName: formData.assetName,
          assetCode: formData.assetCode,
          locationName: formData.locationName,
          assetTypeName: formData.assetTypeName,
          usingDepartmentName: formData.usingDepartmentName,
          usingPersonName: formData.usingPersonName,
          assetBrandName: formData.assetBrandName,
          assetModelNo: formData.assetModelNo?.split("-")[0] || "",
        },
      ]
    : [];
}
//设备显隐
const selectDialog = reactive<DialogOption>({
  visible: false,
  data: [],
});
// 设备选择确认后的回调函数
const changeVisible = (options: any) => {
  if (options && options.length) {
    const data = options[0];
    formData.assetId = data.id;
    formData.assetCode = data.assetCode;
    formData.assetName = data.assetName;
    formData.locationName = data.locationName;
    formData.assetTypeName = data.assetTypeName;
    formData.usingDepartmentName = data.usingDepartmentName;
    formData.usingPersonName = data.usingPersonName;
    if (data.assetModelNo && data.assetBrandName) {
      formData.assetModelNo = `${data.assetModelNo}-${data.assetBrandName}`;
    } else if (data.assetModelNo && !data.assetBrandName) {
      formData.assetModelNo = `${data.assetModelNo}`;
    } else if (!data.assetModelNo && data.assetBrandName) {
      formData.assetModelNo = `${data.assetBrandName}`;
    }
  } else {
    formData.assetId = "";
    formData.assetCode = "";
    formData.assetName = "";
    formData.locationName = "";
    formData.assetTypeName = "";
    formData.usingDepartmentName = "";
    formData.usingPersonName = "";
    formData.assetModelNo = "";
  }
};
// 图片处理
function updateFormFiles(val: []) {
  formData.images = val;
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

//班组
const crewList = ref(<any>[]);
//人员
const memberList = ref(<any>[]);

const changeCrew = async (id: any) => {
  formData.repairTeamId = id;
  if (id) {
    crewList.value.forEach((item: any) => {
      if (item.id === id) {
        formData.repairTeamCode = item.teamCode;
        formData.repairTeamName = item.teamName;
      }
    });
  } else {
    formData.repairTeamCode = "";
    formData.repairTeamName = "";
  }
  formData.repairTeamUserName = "";
  formData.repairTeamUserEmpNo = "";
  formData.repairTeamUser = "";

  memberList.value =
    (await getCrewMemberListApi({ id: formData.repairTeamId })) || [];
};
async function getCrews() {
  crewList.value = (await getCrewListApi({ teamType: "1" })) || [];
}
const changeMember = (id: any) => {
  formData.repairTeamUser = id;
  if (id) {
    memberList.value.forEach((item: any) => {
      if (item.id === id) {
        formData.repairTeamUserEmpNo = item.memberEmpNo;
        formData.repairTeamUserName = item.memberName;
      }
    });
  } else {
    formData.repairTeamUserEmpNo = "";
    formData.repairTeamUserName = "";
  }
};

const promptText = ref("");
const promptStatus: any = ref(null);
const promptReason = ref("");
function getStatusText(status: number) {
  promptReason.value = "";
  if (status === 5) {
    promptText.value = `请确认，是否取消编号为${formData.repairCode}的报修单?`;
  } else if (status === 4) {
    promptText.value = `请确认，编号为${formData.repairCode}的报修单是否维修完成?`;
  } else if (status === 2) {
    promptText.value = `请填写返修原因`;
  } else if (status === 6) {
    promptText.value = `请填写故障关闭原因`;
  }
}
// 选择作业
const showImport = ref(false);
function openPrompt(status: number) {
  promptStatus.value = status;
  getStatusText(status);
  showImport.value = true;
}

// 取消选择
function cancelImport() {
  showImport.value = false;
}

// 返修
function changeStatusReturn() {
  return new Promise(async (resolve, reject) => {
    const res = await request({
      method: "post",
      url: "/eam/equrepairorder/againRepair",
      data: {
        id: formData.id,
        memo: promptReason.value,
      },
    }).catch((e) => {
      // showImport.value = false;
    });
    resolve(res);
  });
}

function changeStatus() {
  return new Promise(async (resolve, reject) => {
    const res = await request({
      method: "post",
      url: "/eam/eamrepairorder/updateStatus",
      data: {
        id: formData.id,
        repairStatus: promptStatus.value,
        memo: promptStatus.value === 6 ? promptReason.value : "",
      },
    }).catch((e) => {
      // showImport.value = false;
    });
    resolve(res);
  });
}
// 追加加工单
async function confirmImport() {
  if (promptStatus.value === 6 && !promptReason.value) {
    ElMessage.error("请填写故障关闭原因");
    return;
  }
  if (promptStatus.value === 2 && !promptReason.value) {
    ElMessage.error("请填写返修原因");
    return;
  }
  if (promptStatus.value === 2) {
    // 返修逻辑独立
    const { code } = await changeStatusReturn();
    if (code === 200) {
      ElMessage.success("操作成功");
      closeDialog();
      emit("reset-table", formData.id);
    } else {
      ElMessage.error("操作失败");
    }
  } else {
    const { code } = await changeStatus();
    if (code === 200) {
      ElMessage.success("操作成功");
      closeDialog();
      emit("reset-table", formData.id);
    } else {
      ElMessage.error("操作失败");
    }
  }
  showImport.value = false;
}

function getRepairOrderPersons(arr: any) {
  let res: any = [];
  arr?.map((e: any) => {
    res.push(e?.personName);
  });
  return res.join("/");
}

// 历史记录获取
const operationRecordList = ref<any>([]);
async function getHistoryList() {
  const res = await request({
    method: "get",
    url: `/eam/eamworkorderrecord/getByOrderId/${formData.id}`,
    data: {},
  }).catch((e) => {});
  operationRecordList.value = res?.data || [];
  console.log("getHistoryList", res);
}

// 排序
const showOperationRecord = () => {
  if (operationRecordList.value.length > 0) {
    operationRecordList.value.reverse();
  }
};

// 返回类型
const typeBack = (data: any) => {
  if (data.operateType == "关闭" || data.operateType == "重新维修") {
    return "danger";
  } else if (
    data.operateType == "转交" ||
    data.operateType == "指派" ||
    data.operateType == "委外开始"
  ) {
    return "warning";
  } else if (data.operateType == "完成确认") {
    return "success";
  } else {
    return "primary";
  }
};

onMounted(() => {
  getCrews();
});
</script>

<style scoped lang="scss">
:deep(.maxhDialog .el-dialog__body) {
  max-height: 70vh;
  overflow-y: auto;
  padding: 10px 20px;
}
.el-form-item {
  margin-bottom: 15px;
}
:deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
  width: 120px;
}
:deep(.el-descriptions__content.el-descriptions__cell.is-bordered-content) {
  min-width: 180px;
}
:deep(.el-upload--picture-card) {
  width: 130px;
  height: 130px;
}
:deep(.el-upload-list__item) {
  width: 130px;
  height: 130px;
}
:deep(.showImport .el-dialog__body) {
  padding: 20px;
}
</style>
